import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'abc',
      redirect: '/home/manage',
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
    },
    {
      path: '/home',
      name: 'home',
      redirect: '/home/manage',
      component: () => import('../views/HomeView.vue'),
      children: [
        {
          path: 'manage',
          name: 'manage',
          component: () => import('../views/GoodsMandeView.vue'),
        },
        {
          path: 'add',
          name: 'add',
          component: () => import('../views/GoodsAddView.vue'),
        },
        {
          path: 'edit/:id',
          name: 'edit',
          component: () => import('../views/GoodsEditView.vue'),
        },
        {
          path: 'contact',
          name: 'contact',
          component: () => import('../views/ContactView.vue'),
        },
      ],
    },
    {
      path: '/:NotFound(.*)*',
      name: 'NotFound',
      component: () => import('../views/NotFoundView.vue'),
    },
  ],
})

//设置导航守卫
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin')

  if (isLogin) {
    next()
  } else {
    if (to.path !== '/login') {
      alert('请先登录！')
      next('/login')
    } else {
      next()
    }
  }
})

export default router
